package whf.framework.meta;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import whf.framework.util.StringUtils;
import whf.framework.util.Utils;

/**
 * @author wanghaifeng
 *
 */
public class XmlMetaParser implements IMetaParser{

	private static Class newClass(String packageName, String type, String className){
		if(className.indexOf(".") == -1){
			return Utils.getClassByClassName(packageName + "."+type+"." + className);
		} else {
			return Utils.getClassByClassName(className);
		}
	}
	
	public List<Meta> listMetas() throws MetaParserException {
		List<Meta> metas = new ArrayList<Meta>();
		
		String metaPath = MetaFactory.class.getPackage().getName();
		metaPath = StringUtils.replace(metaPath,".","/");
		SAXBuilder builder = new SAXBuilder();
		InputStream is = Meta.class.getClassLoader().getResourceAsStream(
				metaPath+"/BOMeta.xml");
		try {
			Document document = builder.build(is);
			List list = document.getRootElement().getChildren("meta");
			List<Element> metaElements = new ArrayList<Element>();
			for(int i=0; i<list.size(); i++){
				metaElements.add((Element)list.get(i));
			}
			for (Element meta:metaElements) {
				String packageName = meta.getAttributeValue("package");
				int id = Integer.parseInt(meta.getChildText("id"));
				String name = meta.getChildText("name");
				String description = meta.getChildText("description");
				String serviceName = meta.getChildText("serviceName");
				String daoName = meta.getChildText("daoName");
				String persistenceTable = meta.getChildText("persistenceTable");

				Class modelClass = newClass(packageName,"entity", meta.getChildText("modelClass"));
				Class serviceClass = newClass(packageName,"service", meta.getChildText("serviceClass"));
				Class actionClass = newClass(packageName,"web", meta.getChildText("actionClass"));
				Class daoClass = newClass(packageName,"dao", meta.getChildText("daoClass"));
				Class parentModelClass = newClass(packageName,"dao", meta.getChildText("parentModelClass"));

				String validationName = meta.getChildText("validationName");

				Meta boMeta = new Meta(id, name, description, serviceName,
						daoName, validationName, persistenceTable, modelClass,
						actionClass, serviceClass, daoClass, parentModelClass, null);
				metas.add(boMeta);
			}
		} catch (Exception e) {
			throw new MetaParserException(e);
		}
		return metas;
	}

}
